<template>
  <div>
    <h1>这是App根组件</h1>
    <!-- MyTable 表格组件 -->
    <my-table :data="dataList">
      <template #header>
        <th>序号</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <template #body="{row, index}">
        <td>{{ index + 1 }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            type="text"
            class="form-control from-control-sm form-ipt"
            v-if="row.inputVisible"
            v-focus
            v-model.trim="row.inputValue"
            @blur="onInputChange(row)"
            @keyup.enter="onInputChange(row)"
            @keyup.esc="row.inputValue=''"
          />
          <button type="button" class="btn btn-primary btn-sm" v-else @click="row.inputVisible = true">+Tag</button>
          <!-- 循环渲染标签信息 -->
          <span class="badge badge-warning ml-2" v-for="(item,index) in row.tags" :key="index">{{item}}</span>
        </td>
        <td>
          <button type="button" class="btn btn-danger btn-sm" @click="remove(row.id)">删除</button>
        </td>
      </template>
    </my-table>
  </div>
</template>

<script>
import MyTable from './components/my-table/MyTable.vue'

export default {
  name: 'MyApp',
  components: { MyTable },
  directives: {
    focus(el) {
      el.focus()
    }
  },
  created() {
    this.getDataList()
  },
  data() {
    return {
      // 商品列表数据
      dataList: []
    }
  },
  methods: {
    // 请求列表数据
    async getDataList() {
      const { data: res } = await this.$http.get('/api/goods')
      if (res.status !== 0) return alert('获取商品数据失败')
      this.dataList = res.data
    },
    // 删除商品
    remove(id) {
      this.dataList = this.dataList.filter(x => x.id !== id)
    },
    onInputChange(row) {
      const val = row.inputValue
      row.inputValue = ''
      row.inputVisible = false
      if (!val || row.tags.indexOf(val) !== -1) return
      row.tags.push(val)
    }
  }
}
</script>

<style lang="less" scoped>
.form-ipt {
  width: 80px;
  display: inline;
}
</style>